<template>
  <my-page title="瑞安国企资产小程序—瑞安国企资产e租" :is-back="false" :is-tabbar="true" :tabKey="2">
    <!-- 地图区域 - 全屏展示 -->
    <view class="map-container">
      <map
        id="map"
        class="asset-map"
        :latitude="mapCenter.latitude"
        :longitude="mapCenter.longitude"
        :markers="markers"
        :scale="mapScale"
        show-location
        @markertap="onMarkerTap"
      ></map>
    </view>
    
    <!-- 控制卡片 - 绝对定位 -->
    <view class="control-card" :style="{top: topPosition + 'px'}">
      <!-- 搜索框 -->
      <view class="search-box">
        <view class="search-input-container">
          <text class="iconfont icon-search"></text>
          <uni-easyinput 
            :inputBorder="false" 
            v-model="keyword" 
            type="text" 
            class="search-input" 
            placeholder="请输入房屋名称/地区筛选" 
            @confirm="handleSearch"
          />
          <text class="search-btn" @tap="handleSearch">搜索</text>
        </view>
      </view>
      
      <!-- 筛选栏 -->
      <view class="filter-bar">
        <my-picker
          :data="typeFilterData"
          v-model="filterParams.type"
          title="选择类型"
          placeholder="类型"
          :clearable="true"
          class="filter-picker"
          @change="handleTypeChange"
        ></my-picker>
        
        <my-picker
          :data="priceFilterData"
          v-model="priceFilterValue"
          title="选择出租价格范围"
          placeholder="出租价格"
          :clearable="true"
          class="filter-picker"
          @change="handlePriceChange"
        ></my-picker>
        
        <my-picker
          :data="transferPriceFilterData"
          v-model="transferPriceFilterValue"
          title="选择出售价格范围"
          placeholder="出售价格"
          :clearable="true"
          class="filter-picker"
          @change="handleTransferPriceChange"
        ></my-picker>
        
        <my-picker
          :data="areaFilterData"
          v-model="areaFilterValue"
          title="选择面积范围"
          placeholder="面积"
          :clearable="true"
          class="filter-picker"
          @change="handleAreaChange"
        ></my-picker>
        
        <my-picker
          :data="regionFilterData"
          v-model="filterParams.streetName"
          title="选择区域"
          placeholder="区域"
          :clearable="true"
          class="filter-picker"
          @change="handleRegionChange"
        ></my-picker>
      </view>
      
      <!-- 状态栏 -->
      <view class="status-tabs">
        <view 
          class="status-tab" 
          :class="{ active: activeStatus === 'all' }"
          @click="changeStatus('all')"
        >
          全部资产
        </view>
        <view 
          class="status-tab" 
          v-for="(statusItem, index) in assetStatusData" 
          :key="index"
          :class="{ active: activeStatus === statusItem.value }"
          @click="changeStatus(statusItem.value)"
        >
          {{statusItem.label}}
        </view>
      </view>
    </view>
    
    <!-- 底部资产预览卡片 -->
    <view class="bottom-card" v-if="selectedAsset">
      <image class="asset-img" :src="getImageUrl(selectedAsset.imageUrl)" mode="aspectFill"></image>
      <view class="asset-info" @tap="navigateToDetail">
        <view class="asset-name">{{selectedAsset.name}}</view>
        <view class="asset-meta">
          <text class="asset-area">{{selectedAsset.area}}</text>
          <text class="asset-type">{{getTypeName(selectedAsset.type)}}</text>
        </view>
        <view class="price-container">
          <text class="asset-price" v-if="shouldShowRentPrice(selectedAsset)">出租价格:{{selectedAsset.rent}}</text>
          <text class="asset-price transfer-price" v-if="shouldShowTransferPrice(selectedAsset)">出售价格:{{selectedAsset.transferPrice}}</text>
        </view>
      </view>
      <view class="nav-btn" @tap="navigateToAsset">
        <image :src="'/static/images/location_1.png'" mode="aspectFit" class="nav-icon"></image>
        <text>一键导航</text>
      </view>
    </view>
  </my-page>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { getAssetList } from '@/api/assets';
import { getDictData } from '@/api/system';
import MyPicker from '@/components/MyPicker.vue';

// 获取状态栏高度
const statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
// 计算导航栏下方位置（导航栏高度 + 状态栏高度）
const topPosition = computed(() => statusBarHeight + 60); // 单位是px，120rpx=60px

// 搜索关键词
const keyword = ref('');

// 筛选相关
const activeStatus = ref('all');

// 筛选数据
const typeFilterData = ref([]);
const assetStatusData = ref([]);
const priceFilterData = ref([]);
const transferPriceFilterData = ref([]);
const areaFilterData = ref([]);
const regionFilterData = ref([]);

// 筛选值
const priceFilterValue = ref(null);
const transferPriceFilterValue = ref(null);
const areaFilterValue = ref(null);

// 地图相关
const mapCenter = reactive({
  latitude: 27.7865, // 默认瑞安市中心坐标
  longitude: 120.6361
});
const mapScale = ref(13); // 将默认缩放级别改为13，使地图更加聚焦在瑞安市区

// 标记点数据
const markers = ref([]);
// 资产列表
const assetList = ref([]);
// 选中的资产
const selectedAsset = ref(null);
// 资产类型字典
const typeDict = ref([]);
// 加载状态
const loading = ref(false);

// 筛选参数
const filterParams = reactive({
  keyword: '',
  type: null,
  priceMin: null,
  priceMax: null,
  transferPriceMin: null,
  transferPriceMax: null,
  areaMin: null,
  areaMax: null,
  streetName: null,
  assetStatus: null
});

// 切换状态
const changeStatus = (status) => {
  activeStatus.value = status;
  
  // 根据当前选择的状态设置状态参数
  if (status === 'all') {
    filterParams.assetStatus = null;
  } else {
    // 直接使用字典中的状态值
    filterParams.assetStatus = parseInt(status);
  }
  
  // 重置选中的资产
  selectedAsset.value = null;
  loadAssetsByStatus(status);
};

// 根据状态加载资产
const loadAssetsByStatus = async (status) => {
  loading.value = true;
  uni.showLoading({
    title: '加载数据中...'
  });
  
  try {
    // 构建查询参数
    const params = {
      pageNum: 1,
      pageSize: 999,
      keyword: keyword.value,
      type: filterParams.type,
      rentMin: filterParams.priceMin,
      rentMax: filterParams.priceMax,
      transferPriceMin: filterParams.transferPriceMin,
      transferPriceMax: filterParams.transferPriceMax,
      areaMin: filterParams.areaMin,
      areaMax: filterParams.areaMax,
      streetName: filterParams.streetName,
      assetStatus: filterParams.assetStatus
    };
    
    // 调用API获取资产列表
    const res = await getAssetList(params);
    if (res && res.rows) {
      assetList.value = res.rows;
      updateMarkers();
      
      if(assetList.value.length === 0) {
        uni.showToast({
          title: '未找到符合条件的资产',
          icon: 'none',
          duration: 2000
        });
      }
    } else {
      assetList.value = [];
      markers.value = [];
      uni.showToast({
        title: '获取资产数据失败',
        icon: 'none',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('加载资产失败', error);
    assetList.value = [];
    markers.value = [];
    uni.showToast({
      title: '获取资产数据失败',
      icon: 'none',
      duration: 2000
    });
  } finally {
    loading.value = false;
    uni.hideLoading();
  }
};

// 获取用户当前位置
const getUserLocation = () => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('获取位置成功', res);
        mapCenter.latitude = res.latitude;
        mapCenter.longitude = res.longitude;
        resolve(res);
      },
      fail: (err) => {
        console.error('获取位置失败', err);
        reject(err);
      }
    });
  });
};

// 处理搜索
const handleSearch = () => {
  filterParams.keyword = keyword.value;
  // 重置选中的资产
  selectedAsset.value = null;
  loadAssetsByStatus(activeStatus.value);
};

// 点击标记点
const onMarkerTap = (e) => {
  const markerId = e.detail.markerId;
  const asset = assetList.value.find(item => item.id === markerId);
  if (asset) {
    selectedAsset.value = asset;
  // 设置地图中心为选中资产位置
   mapCenter.latitude = asset.latitude;
   mapCenter.longitude = asset.longitude;
    // // 创建地图上下文，将地图中心移动到选中的标记点
    // const mapContext = uni.createMapContext('map');
    // if (mapContext && mapContext.moveToLocation) {
    //   mapContext.moveToLocation({
    //     latitude: asset.latitude,
    //     longitude: asset.longitude,
    //     success: () => {
    //       console.log('移动地图到标记点成功');
    //     },
    //     fail: (err) => {
    //       console.error('移动地图到标记点失败', err);
    //     }
    //   });
    // }
  }
};

// 导航到资产位置
const navigateToAsset = () => {
  if (!selectedAsset.value) return;
  
  uni.openLocation({
    latitude: parseFloat(selectedAsset.value.latitude),
    longitude: parseFloat(selectedAsset.value.longitude),
    name: selectedAsset.value.name,
    address: selectedAsset.value.address || '暂无详细地址',
    success: () => {
      console.log('打开位置成功');
    },
    fail: (err) => {
      console.error('打开位置失败', err);
      uni.showToast({
        title: '导航失败，请重试',
        icon: 'none'
      });
    }
  });
};

// 跳转到资产详情页面
const navigateToDetail = () => {
  if (!selectedAsset.value) return;
  
  uni.navigateTo({
		url: `/pages/asset/detail?id=${selectedAsset.value.id}`
	})
};

// 获取资产类型名称
const getTypeName = (typeCode) => {
  const type = typeDict.value.find(item => item.dictValue === typeCode);
  return type ? type.dictLabel : '其他';
};

// 筛选变化处理函数
const handleTypeChange = (value) => {
  // 如果是字符串值，需要转换为数字
  if (value.values[0] !== null && typeof value.values[0] === 'string') {
    filterParams.type = parseInt(value.values[0]);
  } else {
    filterParams.type = value.values[0];
  }
  loadAssetsByStatus(activeStatus.value);
};

const handlePriceChange = (value) => {
  if (value.values[0]) {
    const [min, max] = value.values[0].split('-');
    filterParams.priceMin = min;
    filterParams.priceMax = max.length ? max : null;
  } else {
    filterParams.priceMin = null;
    filterParams.priceMax = null;
  }
  loadAssetsByStatus(activeStatus.value);
};

const handleTransferPriceChange = (value) => {
  if (value.values[0]) {
    const [min, max] = value.values[0].split('-');
    filterParams.transferPriceMin = min;
    filterParams.transferPriceMax = max.length ? max : null;
  } else {
    filterParams.transferPriceMin = null;
    filterParams.transferPriceMax = null;
  }
  loadAssetsByStatus(activeStatus.value);
};

const handleAreaChange = (value) => {
  if (value.values[0]) {
    const [min, max] = value.values[0].split('-');
    filterParams.areaMin = min;
    filterParams.areaMax = max.length ? max : null;
  } else {
    filterParams.areaMin = null;
    filterParams.areaMax = null;
  }
  loadAssetsByStatus(activeStatus.value);
};

const handleRegionChange = (value) => {
  if (value.values[0]) {
    filterParams.streetName = value.values[0];
  } else {
    filterParams.streetName = null;
  }
  loadAssetsByStatus(activeStatus.value);
};

// 加载资产类型字典
const loadTypeDict = async () => {
  try {
    const res = await getDictData('sys_asset_type');
    if (res && res.data) {
      typeDict.value = res.data;
    }
  } catch (error) {
    console.error('加载资产类型字典失败', error);
  }
};

// 初始化字典数据
const initDictData = async () => {
  try {
    // 获取资产类型字典
    const assetTypeRes = await getDictData('asset_type');
    if (assetTypeRes.code === 200 && assetTypeRes.data) {
      typeFilterData.value = assetTypeRes.data.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }));
      // 添加"不限"选项
      typeFilterData.value.push({ label: '不限', value: null });
    }
    
    // 获取资产状态字典
    const assetStatusRes = await getDictData('asset_status');
    if (assetStatusRes.code === 200 && assetStatusRes.data) {
      // 只获取启用状态的字典项（status为'0'表示启用）
      const enabledStatusData = assetStatusRes.data.filter(item => item.status === '0');
      assetStatusData.value = enabledStatusData.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }));
    }
    
    // 获取租金范围字典
    const rentRes = await getDictData('sys_rent');
    if (rentRes.code === 200 && rentRes.data) {
      priceFilterData.value = rentRes.data.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }));
      // 添加"不限"选项
      priceFilterData.value.push({ label: '不限', value: null });
    }
    
    // 获取出让价格范围字典
    const transferPriceRes = await getDictData('sys_transfer_price');
    if (transferPriceRes.code === 200 && transferPriceRes.data) {
      transferPriceFilterData.value = transferPriceRes.data.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }));
      // 添加"不限"选项
      transferPriceFilterData.value.push({ label: '不限', value: null });
    }
    
    // 获取面积范围字典
    const areaRes = await getDictData('sys_area');
    if (areaRes.code === 200 && areaRes.data) {
      areaFilterData.value = areaRes.data.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }));
      // 添加"不限"选项
      areaFilterData.value.push({ label: '不限', value: null });
    }
    
    // 获取区域字典
    const streetRes = await getDictData('sys_street');
    if (streetRes.code === 200 && streetRes.data) {
      regionFilterData.value = streetRes.data.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }));
      // 添加"不限"选项
      regionFilterData.value.push({ label: '不限', value: null });
    }
  } catch (error) {
    console.error('加载字典数据失败', error);
    uni.showToast({
      title: '加载数据失败，请稍后再试',
      icon: 'none',
      duration: 2000
    });
  }
};

// 重置筛选
const resetFilter = () => {
  filterParams.type = null;
  filterParams.priceMin = null;
  filterParams.priceMax = null;
  filterParams.transferPriceMin = null;
  filterParams.transferPriceMax = null;
  filterParams.areaMin = null;
  filterParams.areaMax = null;
  filterParams.streetName = null;
  priceFilterValue.value = null;
  transferPriceFilterValue.value = null;
  areaFilterValue.value = null;
};

// 初始化数据
onMounted(async () => {
  // 加载字典数据
  await loadTypeDict();
  await initDictData();
  
  // 设置地图中心为瑞安
  mapCenter.latitude = 27.7865;
  mapCenter.longitude = 120.6361;
  // 加载资产数据
  loadAssetsByStatus('all');
});

// 更新地图标记
const updateMarkers = () => {
  if (assetList.value.length === 0) {
    markers.value = [];
    return;
  }
  
  markers.value = assetList.value.map((asset) => ({
    id: asset.id,
    latitude: asset.latitude,
    longitude: asset.longitude,
    iconPath: asset.assetStatus === 1 ? '/static/images/location_1.png' : '/static/images/location_2.png',
    width: 40,
    height: 50,
    joinCluster: false,
    callout: {
      content: asset.name,
      color: '#333333',
      fontSize: 12,
      borderRadius: 4,
      padding: 5,
      display: 'BYCLICK',
      textAlign: 'center'
    }
  }));

};

// 判断是否应该显示出租价格
const shouldShowRentPrice = (asset) => {
  if (!asset) return false
  
  const method = asset.revitalizationMethod
  const hasRentPrice = asset.rent
  
  if (!hasRentPrice) return false
  
  return method === '出租' || method === '租售均可'|| method === '先租后让'
}

// 判断是否应该显示出售价格
const shouldShowTransferPrice = (asset) => {
  if (!asset) return false
  
  const method = asset.revitalizationMethod
  const hasTransferPrice = asset.transferPrice
  
  if (!hasTransferPrice) return false
  
  return method === '出售' || method === '租售均可'|| method === '先租后让'
}

// 在script部分添加getImageUrl函数
const getImageUrl = (imageUrl) => {
	// 处理null、undefined或空字符串的情况
	if (!imageUrl) return '/static/images/suoluetu.png'
	
	// 确保imageUrl是字符串类型
	if (typeof imageUrl !== 'string') {
		return '/static/images/suoluetu.png'
	}
	
	try {
		// 分割图片URL，取第一个
		const firstImage = imageUrl.split(',')[0]
		
		// 检查是否已包含http
		if (firstImage.startsWith('http')) {
			return firstImage
		}
		
		// 拼接基础URL
		return import.meta.env.VITE_APP_BASE_API + firstImage
	} catch (error) {
		console.error('处理图片URL出错:', error)
		return '/static/images/suoluetu.png'
	}
}
</script>

<style lang="scss">
@import '@/static/styles/index.scss';

::v-deep .my_page {
  .my_header {
    background: linear-gradient(to right, #2979ff, #1565C0);
    .wrap {
      background: linear-gradient(to right, #2979ff, #1565C0);
    }
  }
}

/* 地图容器 - 铺满整个页面 */
.map-container {
  width: 100%;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

.asset-map {
  width: 100%;
  height: 100%;
}

/* 控制卡片 - 绝对定位 */
.control-card {
  position: absolute;
  /* top通过动态样式设置 */
  left: 30rpx;
  right: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  overflow: hidden;
  z-index: 10;
}

/* 搜索框部分 */
.search-box {
  padding: 20rpx;
  background-color: #fff;
  
  .search-input-container {
    height: 72rpx;
    border: 1rpx solid #eeeeee;
    border-radius: 36rpx;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    
    .iconfont {
      color: #999;
      font-size: 32rpx;
      margin-right: 10rpx;
    }
    
    .search-input {
      flex: 1;
      height: 72rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    .search-btn {
      margin-left: 20rpx;
      color: #fff;
      font-size: 30rpx;
      background: rgba(4, 96, 242, 1);
      width: 100rpx;
      height: 60rpx;
      line-height: 60rpx;
      border-radius: 30rpx;
      text-align: center;
      margin-right: -20rpx;
    }
  }
}

/* 筛选栏部分 */
.filter-bar {
  display: flex;
  justify-content: space-around;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #f5f5f5;
}

/* 状态标签部分 */
.status-tabs {
  display: flex;
  padding: 20rpx;
  
  .status-tab {
    flex: 1;
    padding: 15rpx 0;
    font-size: 28rpx;
    color: #333;
    text-align: center;
    margin-right: 20rpx;
    border-radius: 30rpx;
    background-color: #f5f5f5;
    
    &:last-child {
      margin-right: 0;
    }
    
    &.active {
      color: #fff;
      background-color: #2979ff;
      font-weight: normal;
    }
  }
}

.bottom-card {
  position: fixed;
  bottom: calc(160rpx + constant(safe-area-inset-bottom)); /* iOS < 11.2 */
  bottom: calc(160rpx + env(safe-area-inset-bottom)); /* iOS >= 11.2 */
  left: 30rpx;
  right: 30rpx;
  height: 180rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
  z-index: 100;
}

.asset-img {
  width: 180rpx;
  height: 180rpx;
}

.asset-info {
  flex: 1;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.asset-info::after {
  content: '';
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 16rpx;
  height: 16rpx;
  border-top: 2rpx solid #999;
  border-right: 2rpx solid #999;
  transform: translateY(-50%) rotate(45deg);
}

.asset-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.asset-meta {
  display: flex;
  margin-bottom: 10rpx;
}

.asset-area {
  font-size: 24rpx;
  color: #666;
  margin-right: 20rpx;
}

.asset-type {
  font-size: 24rpx;
  color: #666;
}

.price-container {
  display: flex;
  flex-direction: column;
}

.asset-price {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.transfer-price {
  color: #ff9500;
  font-size: 28rpx;
  margin-top: 5rpx;
}

.nav-btn {
  width: 120rpx;
  height: 180rpx;
  background-color: #3a86ff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 24rpx;
}

.nav-icon {
  width: 48rpx;
  height: 48rpx;
  margin-bottom: 10rpx;
}
</style>